package hu.dynamicwebshop.daos.impls;

import hu.dynamicwebshop.daos.CountryDAO;
import hu.dynamicwebshop.entities.Country;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author Szecskó Zoltán <zoltan.szecsko@gmail.com>
 */
public class CountryDAOImpl implements Serializable, CountryDAO {

    private static final long serialVersionUID = 1L;
    private Session session;
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Country> findAll() {
        examineSession();

        session.beginTransaction();

        @SuppressWarnings("unchecked")
        List<Country> results = session.createCriteria(Country.class).list();

        session.close();
        return results;
    }

    private void examineSession() {
        if (session == null) {
            setSession();
        } else if (!session.isOpen()) {
            session = session.getSessionFactory().openSession();
        }
    }

    private void setSession() {
        this.session = sessionFactory.openSession();
    }

    @Override
    public Country findByName(String countryName) {
        examineSession();

        session.beginTransaction();

        Criteria c = session.createCriteria(Country.class)
                .add(Restrictions.like("countryName", countryName));

        Country result = (Country) c.list().get(0);

        session.close();
        return result;
    }
}
